﻿using SqlSugar;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Reflection;
using System.Text;

namespace DataMapper
{
    public class GetWhere
    {
        /// <summary>
        /// 获取sql条件，泛型
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public string GetSql<T>(T entity)
        {
            if (entity == null) throw new Exception("类型为空！");
            Type type = entity.GetType();

            StringBuilder sql = new StringBuilder("  1=1");

            foreach (PropertyInfo item in type.GetProperties())
            {
                var values = item.GetValue(entity, null);

                //剔除空值和空日期及0值
                if (values == null || values == DBNull.Value) continue;
                if (values == null) continue;
                if (values.ToString() == "0") continue;
                if (values.ToString().StartsWith("0001")) continue;//空日期

                Console.WriteLine(item.Name + "=" + GetTypeValue(values));
                sql.Append(" and ");
                sql.Append($"{item.Name}={ GetTypeValue(values)}");
            }

            return sql.ToString();
        }

        /// <summary>
        ///  获取sql条件，Hashtable
        /// </summary>
        /// <param name="whereEntity">要查询的条件ht</param>
        /// <returns></returns>
        public string GetSql(Hashtable whereEntity)
        {
            StringBuilder sql = new StringBuilder("  1=1");
            foreach (DictionaryEntry item in whereEntity)
            {
                var values = item.Value;

                //剔除空值和空日期的字段
                if (values == null || values == DBNull.Value||string.IsNullOrWhiteSpace(values.ToString())) continue;
                if (values == null) continue;
                if (values.ToString().StartsWith("0001")) continue;//空日期

                //Console.WriteLine(item.Key + "=" + GetTypeValue(values));
                sql.Append(" and ");
                sql.Append($"{item.Key}={ GetTypeValue(values)}");
            }
            return sql.ToString();
        }


        private dynamic GetTypeValue(object obj)
        {
            var typeName = obj.GetType().Name;
            if (typeName == "String" || typeName == "DateTime")
            {
                return $"'{obj}'";
            }
            else if (typeName == "Boolean")
            {
                return ((Boolean)obj) ? 0 : 1;
            }
            else
            {
                return obj;
            }
        }
    }
}
